import 'package:stacked/stacked.dart';
import 'package:vista/shared/models/moment_shot.dart';
import 'package:vista/shared/models/user_frame.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/services/post_studio.dart';

/// 图片详情视图模型
/// 管理图片详情页面的数据和状态
class ImageDetailViewModel extends BaseViewModel {
  final AuthFocus _authFocus;
  final PostStudio _postStudio;
  final String postId;

  ImageDetailViewModel(this._authFocus, this._postStudio, this.postId);

  MomentShot? _post;
  MomentShot? get post => _post;

  UserFrame? _author;
  UserFrame? get author => _author;

  int _currentImageIndex = 0;
  int get currentImageIndex => _currentImageIndex;

  bool _isLiked = false;
  bool get isLiked => _isLiked;

  int _likeCount = 0;
  int get likeCount => _likeCount;

  UserFrame? _currentUser;
  UserFrame? get currentUser => _currentUser;

  /// 初始化数据
  Future<void> initialize() async {
    setBusy(true);
    try {
      await _loadPost();
      await _loadAuthor();
      await _loadCurrentUser();
      await _loadLikeStatus();
    } finally {
      setBusy(false);
    }
  }

  /// 加载动态
  Future<void> _loadPost() async {
    _post = await _postStudio.getPostById(postId);
    notifyListeners();
  }

  /// 加载发布者信息
  Future<void> _loadAuthor() async {
    if (_post == null) return;
    final users = await _authFocus.getUsers();
    try {
      _author = users.firstWhere((user) => user.id == _post!.authorId);
    } catch (e) {
      _author = null;
    }
    notifyListeners();
  }

  /// 加载当前用户
  Future<void> _loadCurrentUser() async {
    _currentUser = await _authFocus.getCurrentUser();
    notifyListeners();
  }

  /// 加载点赞状态
  Future<void> _loadLikeStatus() async {
    if (_post == null) return;

    if (_currentUser != null) {
      _isLiked = await _postStudio.isLiked(postId, _currentUser!.id);
    }
    _likeCount = await _postStudio.getLikeCount(postId);
    notifyListeners();
  }

  /// 切换图片索引
  void setImageIndex(int index) {
    if (_post == null) return;
    if (index >= 0 && index < _post!.images.length) {
      _currentImageIndex = index;
      notifyListeners();
    }
  }

  /// 切换点赞
  Future<void> toggleLike() async {
    if (_currentUser == null || _post == null) return;

    if (_isLiked) {
      await _postStudio.unlikePost(_post!.id, _currentUser!.id);
    } else {
      await _postStudio.likePost(_post!.id, _currentUser!.id);
    }

    _isLiked = !_isLiked;
    _likeCount = await _postStudio.getLikeCount(_post!.id);
    notifyListeners();
  }

  /// 刷新认证和点赞状态
  Future<void> refreshAuthAndLikeStatus() async {
    await _loadCurrentUser();
    await _loadLikeStatus();
  }
}
